<template>
    <div class="container">
        +86 <input type="text" placeholder="输入手机号" v-model="phonenumber" />
        <input type="text" placeholder="请输入校验码" v-model="verificationCode" />
        <button @click.prevent="sendVerificationCode" class="send-code" :disabled="countdown > 0">
            {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
        </button>
    </div>
</template>

<script setup lang="ts">
import { ref,  } from 'vue';
import axios from 'axios'

const errorMessage = ref('')
const phonenumber = ref('')
const verificationCode = ref('')
const countdown = ref(0)
const correctCode = ref('')

function clearErrorMessage() {
    setTimeout(() => {
        errorMessage.value = ''
    }, 2000)
}

function startCountdown() {
    countdown.value = 60
    const timer = setInterval(() => {
        countdown.value--
        if (countdown.value === 0) clearInterval(timer)
    }, 1000)
}

function sendVerificationCode() {
    if (!/^1[3-9]\d{9}$/.test(phonenumber.value)) {
        errorMessage.value = '请输入有效的手机号码❌'
        clearErrorMessage()
        return
    }

    if (countdown.value > 0) return

    startCountdown()

    axios.get(`http://localhost:3000/code?phoneNum=${phonenumber.value}`)
        .then(res => {
            correctCode.value = res.data.code
            console.log('验证码为:', correctCode.value)
        })
        .catch(err => {
            console.error('Error:', err)
        })
}

</script>

<style scoped>
.container {
    padding: 20px;
    max-width: 300px;
    margin: 0 auto;
}

.error {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 10px;
}

:deep(.el-button) {
    width: 100%;
    margin-top: 10px;
}

:deep(.el-input) {
    margin-bottom: 10px;
}
</style>